Closure refers to a feature which is used to allow any function for remembering and accessing the lexical scope of it in time of execution of it outside of that scope as well. This means that any function which can be used to maintain the access to the variables as well as parameters from the parent function and after the complete execution of that parent function as well.
An example of closure in JavaScript is as follows:
function outerFunction() {
var outerVariable = "I am outside!";
function innerFunction() {
var innerVariable = "I am inside!";
console.log(outerVariable);
console.log(innerVariable);
}
return innerFunction;
}
var innerFunc = outerFunction();
innerFunc();
Here in the mentioned example the outerFunction is used to return the innerFunction as a output. When the call of outerFunction takes place then it creates variable called as outerVariable and a specific function called as innerFunction. This innerFunction is used to create innerVariable.
The execution of innerFunction logs the value of outerVariable as well as innerVariable to the console. The innerFunction is used to maintain the access to the outerVariable because of closure.
Amrita Bhattacharjee
28-Mar-2023Closure refers to a feature which is used to allow any function for remembering and accessing the lexical scope of it in time of execution of it outside of that scope as well. This means that any function which can be used to maintain the access to the variables as well as parameters from the parent function and after the complete execution of that parent function as well.
An example of closure in JavaScript is as follows:
Here in the mentioned example the outerFunction is used to return the innerFunction as a output. When the call of outerFunction takes place then it creates variable called as outerVariable and a specific function called as innerFunction. This innerFunction is used to create innerVariable.
The execution of innerFunction logs the value of outerVariable as well as innerVariable to the console. The innerFunction is used to maintain the access to the outerVariable because of closure.